<?php
/**
 * Created by PhpStorm.
 *
 * Author : Traveler.
 * Time   : 2019/12/6 20:58
 * Company: Inner Mongolia Zhengzhi Network Technology Co., Ltd
 */

namespace app\admin\model;


use app\admin\BaseModel;

class Staff extends BaseModel
{
    /**
     * 数据表名称
     * @var string
     */
    protected $table = 'ibms_staff';

    /**
     * 查询字段
     * @var array
     */
    protected $query = [
        'id'        => '=',
        'name'      => 'like',
        'cellphone' => 'like',
        'email'     => 'like',
        'dept_id'   => '=',
        'role_id'   => '=',
        'status'    => '=',
    ];

    /**
     * (静态)获取员工统计
     * @return int
     */
    public static function getStaffCount()
    {
        return static::where('delete_time', 0)->count();
    }

    /**
     * (静态)获取表格渲染数据
     * @param array $param     请求参数
     * @param bool  $isdeleted 删除标记
     * @return array
     */
    public static function getStaffTable(array $param = [], bool $isdeleted = false)
    {
        $model  = new static;
        $with   = ['dept', 'role'];
        $where  = [['delete_time', $isdeleted ? '>' : '=', 0]];
        $filter = $model->filterParam($param, $where);

        return [
            'data'  => $model->where($filter['where'])->withoutField('password')->with($with)
                ->order('id')->page($filter['page'], $filter['limit'])->select(),
            'count' => $model->where($filter['where'])->count()
        ];
    }

    /**
     * (静态)获取所有有效的员工
     * @return \think\Collection
     */
    public static function getValidStaff()
    {
        $where   = ['status' => 1, 'delete_time' => 0];
        $visible = ['id', 'name'];

        return static::where($where)->visible($visible)->order('id')->select();
    }

    /**
     * 模型关联：角色
     * @return \think\model\relation\BelongsTo
     */
    public function role()
    {
        return $this->belongsTo(StaffRole::class, 'role_id');
    }

    /**
     * 模型关联：部门
     * @return \think\model\relation\BelongsTo
     */
    public function dept()
    {
        return $this->belongsTo(StaffDept::class, 'dept_id');
    }

    /**
     * 获取器：头像默认值
     * @param int $value
     * @return false|string
     */
    public function getAvatarAttr($value)
    {
        return '' != $value ? $value : '/static/images/avatar.png';
    }

    /**
     * 获取器：最后登陆时间
     * @param int $value
     * @return false|string
     */
    public function getLoginTimeAttr($value)
    {
        return $value > 0 ? date('Y-m-d H:i:s', $value) : '';
    }
}